package arrray;

import java.util.Arrays;

/**
 * @author huangxianjin
 * @date 2025/8/3 19:10
 * @description "合并两个有序数组"
 */
public class LC_88 {
    public static void main(String[] args) {
        LC_88 lc88 = new LC_88();
        int[] nums1 = {1, 2, 3, 0, 0, 0};
        int[] nums2 = new int[]{2, 5, 6};
        int m = 3, n = 3;
        lc88.merge1(nums1, m, nums2, n);
    }

    //函数方法1---System.arraycopy（可以在指定位置处复制，而Arrays.copyOf()不可以）
    public void merge1(int[] nums1, int m, int[] nums2, int n) {
        System.arraycopy(nums2, 0, nums1, m, n);
        Arrays.sort(nums1);
    }


    //非函数方法---自己写的（双指针）
    public void merge2(int[] nums1, int m, int[] nums2, int n) {
        int left = 0;
        int right = 0;
        int[] res = new int[m + n];
        int index = 0;
        while (left < m && right < n) {
            if (nums1[left] <= nums2[right]) {
                res[index++] = nums1[left++];
            } else {
                res[index++] = nums2[right++];
            }
        }
        if (left == m) {
            for (int i = right; i < n; i++) {
                res[index++] = nums2[i];
            }
        } else {
            for (int j = left; j < m; j++) {
                res[index++] = nums1[j];
            }
        }

        for (int k = 0; k < res.length; k++) {
            nums1[k] = res[k];
        }
    }

    //官方做法一
    public void merge3(int[] nums1, int m, int[] nums2, int n) {
        for (int i = 0; i != n; ++i) {
            nums1[m + i] = nums2[i];
        }
        Arrays.sort(nums1);
    }

    //官方做法二
    public void merge4(int[] nums1, int m, int[] nums2, int n) {
        int p1 = 0, p2 = 0;
        int[] sorted = new int[m + n];
        int cur;
        while (p1 < m || p2 < n) {
            if (p1 == m) {
                cur = nums2[p2++];
            } else if (p2 == n) {
                cur = nums1[p1++];
            } else if (nums1[p1] < nums2[p2]) {
                cur = nums1[p1++];
            } else {
                cur = nums2[p2++];
            }
            sorted[p1 + p2 - 1] = cur;
        }
        for (int i = 0; i != m + n; ++i) {
            nums1[i] = sorted[i];
        }
    }
}
